﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using log4net;
using YetAnotherChat.Common;
using YetAnotherChat.MemoryStorage.Interfaces;

namespace YetAnotherChat.MemoryStorage.Imp
{
    /// <summary>
    /// A queue class to queue up items for ChatMessageService to periodically same a batch of messages to DB
    /// This queue is for  ChatUI project to use by ChatMessageService class. 
    /// </summary>
    public class MemoryQueueStorage: IMemoryQueueStorage
    {
        private ConcurrentQueue<EntityBase> _internalQueue;

        private static object _lock = new object();

        public MemoryQueueStorage()
        {
            _internalQueue = new ConcurrentQueue<EntityBase>();
        }

        public void Queue(Common.EntityBase entity)
        {
            _internalQueue.Enqueue(entity);
        }

        public void Queue(Common.EntityBase[] entities)
        {
            foreach (var e in entities)
            {
                _internalQueue.Enqueue(e);
            }
        }

        public Common.EntityBase[] Dequeue(int itemCount)
        {
            var items = new List<EntityBase>();
            for (var i = 0; i < itemCount && _internalQueue.Count >= 0; i++)
            {
                EntityBase r = null;
                if (_internalQueue.TryDequeue(out r))
                {
                    items.Add(r);
                }
            }
            return items.ToArray();
        }


        public int Count
        {
            get { return _internalQueue.Count; }
        }
    }
}
